<template>
  <el-dialog v-model="model" title="修改密码" width="40%">
    <el-form :model="passwordForm" ref="passwordFormRef" label-width="100px">
      <el-form-item label="原密码" prop="oldPassword">
          <el-input v-model="passwordForm.oldPassword" show-password placeholder="请输入原密码"></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input v-model="passwordForm.newPassword" show-password placeholder="请输入新密码"></el-input>
      </el-form-item>
      <el-form-item label="确认新密码" prop="confirmPassword">
        <el-input v-model="passwordForm.confirmPassword" show-password placeholder="请输入确认新密码"></el-input>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="model = false">取 消</el-button>
        <el-button type="primary" @click="submitPasswordChange">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref,watch } from 'vue'
import { ElMessage } from 'element-plus'
import { defineModel } from 'vue'
import axios from 'axios';
axios.defaults.baseURL = "http://localhost:8080";
const model = defineModel()

const passwordForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const emit = defineEmits(['confirm'])

const submitPasswordChange = async() => {
  try {
    const { oldPassword, newPassword, confirmPassword } = passwordForm.value;
    if (!oldPassword) {
      ElMessage.error('请输入原密码');
      return;
    }
    if (!newPassword) {
      ElMessage.error('请输入新密码');
      return;
    }
    if (!confirmPassword) {
      ElMessage.error('请确认新密码');
      return;
    }

    const token = sessionStorage.getItem('token');
    const response = await axios.post('/user/updatePwd', {
      oldpwd: passwordForm.value.oldPassword,  
      newpwd: passwordForm.value.newPassword,  
      isnewpwd:passwordForm.value.confirmPassword
    }, {
      headers: {
        Authorization: `${token}` 
      }
    })

    if (response.data.code === 0) { 
      ElMessage.success('密码修改成功')
      model.value = false
    } else {
      ElMessage.error(response.data.message)
    }
  } catch (error) {
    ElMessage.error('密码修改失败')
    console.error(error)
  }
}
watch(model, (newVal) => {
  if (!newVal) {
    passwordForm.value = {
      oldPassword: '',
      newPassword: '',
      confirmPassword: ''
    }
  }
})
</script>